package com.example.demo_handler

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

/**
 1.handler作用：实现线程间通信
 2.handler运行原理
 （1）Handler
 （2）Looper：
    loop():死循环，从MessageQueue取出消息，并执行Message的target.handleMessage(msg)
 （3）MessageQueue：单向链表，存放Message对象，按照when时间从小到大排序排序
 （4）Message：
    when时间戳
    target标记handler

 a。调用sendMessage方法，将Message(target标记handler)对象加入到MessageQueue
 b。Looper的while死循环不断从MessageQueue取出消息，并执行Message的target.handleMessage(msg)
 */
class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "MainActivity"
    }
    //主线程
    private val handler: Handler = object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                1->{
                    val obj = msg.obj
                    Log.d(TAG, "handleMessage: 数据：$obj")
                }
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //子线程
        Thread{
            val message = Message.obtain()
            message.what = 1
            message.obj = "hahaha"
            handler.sendMessage(message)
            handler.sendMessageDelayed(message,1000)
            handler.sendMessageAtTime(message,System.currentTimeMillis()+1000)
            handler.post(object : Runnable {
                override fun run() {
                    //处理
                }

            })
            handler.postDelayed(object : Runnable {
                override fun run() {
                    //处理
                }

            },2000)
        }.start()

        Thread{
            Looper.prepare()
            val handler = Handler()
            Looper.loop()

        }.start()

    }
}